package org.millioncall.yueyoga.admin.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.millioncall.openplatform.util.StringUtils;
import org.millioncall.yueyoga.admin.dao.TreeNodeDAO;
import org.millioncall.yueyoga.admin.model.TreeNode;
import org.millioncall.yueyoga.admin.service.TreeNodeService;

import com.alibaba.fastjson.JSON;

public class TreeNodeServiceImpl implements TreeNodeService {
	private TreeNodeDAO treeNodeDAO;

	public TreeNodeDAO getTreeNodeDAO() {
		return treeNodeDAO;
	}

	public void setTreeNodeDAO(TreeNodeDAO treeNodeDAO) {
		this.treeNodeDAO = treeNodeDAO;
	}

	/**
	 * 根据id查询整棵树
	 */
	@Override
	public TreeNode findAllTreeById(String treeViewId) {
		List<TreeNode> items = this.treeNodeDAO.findTreeById(treeViewId);

		Map<String, TreeNode> map = new HashMap<String, TreeNode>();
		TreeNode rootNode = null;

		for (int i = 0; i < items.size(); i++) {
			TreeNode node = items.get(i);
			node.setOpen(true);
			if (i == 0) {
				rootNode = node;
			}
			map.put(node.getId(), node);
			if (StringUtils.isNotBlank(node.getParentId())) {
				TreeNode parentNode = map.get(node.getParentId());
				parentNode.getChildNodes().add(node);
			}
		}
		return rootNode;
	}

	@Override
	public String toZTreeJsonString(TreeNode rootNode) {
		String json = JSON.toJSONString(rootNode);
		return json;
	}
}
